package com.kaili.common.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * Created by renzhikun on 18-11-19.
 */
public class VerifyUtil {

    private static final char[] chars = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };
    //字符数量
    private static final int SIZE = 4;
    //干扰线数量
    private static final int LINES = 8;
    //宽度
    private static final int WIDTH = 90;
    //高度
    private static final int HEIGHT = 44;
    //字体大小
    private static final int FONT_SIZE = 30;

    public static Object[] creatImage() {
        StringBuffer sb = new StringBuffer();
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        //获取图片画笔
        Graphics graphics = image.getGraphics();
        //设置画笔颜色
        graphics.setColor(Color.LIGHT_GRAY);
        //绘制矩形背景
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
        Random random = new Random();
        for (int i=0; i<SIZE; i++) {
            int n = random.nextInt(chars.length);
            graphics.setColor(getRandomColor());
            graphics.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
            graphics.drawString(chars[n] + "", i*WIDTH / SIZE, HEIGHT*2/3);
            sb.append(chars[n]);
        }

        for (int i=0; i<LINES; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }
        return new Object[]{sb.toString(), image};
    }

    public static Color getRandomColor() {
        Random random = new Random();
        Color color = new Color(random.nextInt(256),random.nextInt(256), random.nextInt(256));
        return color;
    }
}
